package com.quzi.kettle.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.quzi.kettle.R;
import com.quzi.kettle.activitise.added.TipVoiceActivity;
import com.quzi.kettle.bean.Appoint;
import com.quzi.kettle.utils.MSharePerference;
import com.quzi.kettle.utils.TipvoiceUtil;

public class AlarmService extends Service {
	private static final String TAG = "ServiceDemo";
	public static final String ACTION = "com.quzi.kettle.service.AlarmService";
	private final DateFormat df = new SimpleDateFormat("HH:mm");
	private List<Appoint> appointLists;
	private Date d;
	private Calendar c;
	private Date date;

	@Override
	public IBinder onBind(Intent intent) {
		Log.v(TAG, "ServiceDemo onBind");
		return null;
	}

	@Override
	public void onCreate() {
		Log.v(TAG, "ServiceDemo onCreate");
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.v(TAG, "ServiceDemo onStart");
		super.onStart(intent, startId);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
			//	while (true) {
					appointLists = getAllAppoint();
					d = new Date(System.currentTimeMillis());
					c = Calendar.getInstance();
					c.setTime(d);

					for (int i = 0; i < appointLists.size(); i++) {
						try {
							date = df.parse(appointLists.get(i).getTitle());

							Log.d(TAG,
									date.getHours() + "   " + date.getMinutes()
											+ "   "
											+ c.get(Calendar.HOUR_OF_DAY)
											+ "    " + c.get(Calendar.MINUTE));

							if (date.getHours() == c.get(Calendar.HOUR_OF_DAY)
									&& date.getMinutes() == c
											.get(Calendar.MINUTE)
									&& appointLists.get(i).isStatus()) {
								if (MSharePerference.getInstance(
										getApplicationContext()).getBoolean(
										"remide")) {
									notifyDate();
								}
							}
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
//					try {
//						Thread.sleep(30 * 1000);// sleep for a minute
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
				//}
			}
		}).start();

	}

	private void notifyDate() {
		Log.d(TAG, "NOTIFY!!!");
		CharSequence from = "奇伟智能水壶";
		CharSequence message = "亲~该煮水啦~";

		Intent intent = new Intent();
		ComponentName componentName = new ComponentName("com.quzi.kettlt",
				"com.quzi.kettlt.activitse.MainActivityTest");
		intent.setComponent(componentName);
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.LAUNCHER");
		intent.addFlags(Notification.FLAG_ONGOING_EVENT);

		// The PendingIntent to launch our activity if the user selects this
		// notification
		PendingIntent contentIntent = PendingIntent.getService(this, 0, intent,
				0);
		// construct the Notification object.
		Notification notif = new Notification(R.drawable.ic_launcher, "",
				System.currentTimeMillis());
		notif.flags = Notification.FLAG_ONGOING_EVENT;
		notif.setLatestEventInfo(this, from, message, contentIntent);

		// notification.sound=Uri.parse("android.resource://" + getPackageName()
		// + "/" +R.raw.**);
		// look up the notification manager service

		switch (TipvoiceUtil.getVoiceNo(AlarmService.this)) {
		case -2:
			notif.defaults = Notification.DEFAULT_SOUND;
			break;
		case -1:
			notif.sound = Uri.parse("file://"
					+ Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/audiorecordtest.3gp");
			break;
		default:
			// notif.sound =
			// //Uri.withAppendedPath(RingtoneManager.TYPE_NOTIFICATION, "6");

			RingtoneManager rm = new RingtoneManager(AlarmService.this);
			rm.setType(RingtoneManager.TYPE_NOTIFICATION);
			rm.getCursor();

			notif.sound = rm.getRingtoneUri(TipvoiceUtil
					.getVoiceNo(AlarmService.this));
			// notif.defaults = Notification.DEFAULT_SOUND;
			break;
		}

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.notify(R.string.app_name, notif);

	}

	private List<Appoint> getAllAppoint() {
		String appoints = MSharePerference.getInstance(getApplicationContext())
				.get("appoint");
		List<Appoint> list = new ArrayList<Appoint>();
		if (!appoints.isEmpty()) {
			String[] myappoint = appoints.split(",");
			for (int i = 0; i < myappoint.length; i++) {
				Log.d("appoint", "appoint = " + myappoint[i]);
				String[] mapp = myappoint[i].split("!");
				String title = mapp[0];
				boolean status = mapp[1].equals("true") ? true : false;
				Appoint appoint = new Appoint(title, status);
				list.add(appoint);
			}
		}
		return list;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v(TAG, "ServiceDemo onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
}